<template>
  <div class="distribute-container">
    <div class="distribute-search">
      <span class="page-title">三级分销获利列表</span>

      <el-date-picker v-model="distributeTime" type="daterange" range-separator="至" start-placeholder="获利开始日期"
                      end-placeholder="获利结束日期" class="distribute-time" value-format="yyyy-MM-dd"></el-date-picker>

      <el-input placeholder="请输入搜索内容" v-model="keyWords" class="input-with-select search-keyword">
        <el-select v-model="select" slot="prepend" placeholder="请选择">
          <el-option label="上级用户" value="1"></el-option>
          <el-option label="下级用户" value="2"></el-option>
          <el-option label="资金去向" value="3"></el-option>
          <el-option label="企业名称" value="4"></el-option>
        </el-select>
      </el-input>
      <el-button type="primary" size="small" icon="el-icon-search" @click="searchDistribute">搜索</el-button>
      <el-button type="info" size="small" class="search-keyword-reset" plain @click="resetSearch">重置</el-button>

      <el-button :type="multipleSelection.length > 0?'primary':'info'" size="small" icon="el-icon-edit"
                 @click="toggleSelection(distributeData)" style="margin-right: 10px">批量管理
      </el-button>
      <el-button type="info" size="small" plain @click="toggleSelection()" v-show="multipleSelection.length > 0">
        取消批量管理
      </el-button>

      <div class="excel-inout-box">
        <el-button :loading="downloadLoading" size="mini" type="info" plain icon="el-icon-document"
                   @click="handleExportExcel" v-if="checkPermissionPoints(6) == 1">导出
        </el-button>
      </div>
    </div>

    <!--三级分销获利列表-->
    <div class="distribute-table">
      <el-table ref="multipleTable" :data="distributeData" border stripe fit
                @selection-change="handleSelectionChange" :row-key="getRowKeys"
                v-loading="listLoading" @filter-change="filterChange"
                :row-style="{height:'50px'}" :header-row-style="{height:'40px'}">
        <el-table-column type="selection" :reserve-selection="true" width="40"></el-table-column>
        <el-table-column label="ID" width="100">
          <template slot-scope="scope">
            <span>{{scope.row.id}}</span>
          </template>
        </el-table-column>
        <el-table-column label="上级用户" width="120">
          <template slot-scope="scope">
            <span>{{scope.row.upUserName}}</span>
          </template>
        </el-table-column>
        <el-table-column label="下级用户" width="120">
          <template slot-scope="scope">
            <span>{{scope.row.userName}}</span>
          </template>
        </el-table-column>
        <el-table-column label="企业名称" width="240" show-overflow-tooltip>
          <template slot-scope="scope">
            <span>{{scope.row.mechanismName}}</span>
          </template>
        </el-table-column>
        <el-table-column label="级别" width="120" prop="type"
                         :filters="[{ text: '二级', value: 0 }, { text: '三级', value: 1 }]"
                         :filter-multiple="false" column-key="type"
                         filter-placement="bottom-end">
          <template slot-scope="scope">
            <span>{{scope.row.type | filterType}}</span>
          </template>
        </el-table-column>
        <el-table-column label="获利时间" width="200">
          <template slot-scope="scope">
            <span>{{scope.row.relationMoneyTime}}</span>
          </template>
        </el-table-column>
        <el-table-column label="获利金额" width="100">
          <template slot-scope="scope">
            <span>{{scope.row.relationMoney}}</span>
          </template>
        </el-table-column>
        <el-table-column label="资金去向" width="100">
          <template slot-scope="scope">
            <span>{{scope.row.remark}}</span>
          </template>
        </el-table-column>
        <el-table-column label="资金状态" width="120" prop="delStatus"
                         :filters="[{ text: '待确认', value: 0 }, { text: '待领取', value: 1 }, { text: '已领取', value: 2 }]"
                         :filter-multiple="false" column-key="delStatus"
                         filter-placement="bottom-end">
          <template slot-scope="scope">
            <span>{{scope.row.delStatus | filterStatus}}</span>
          </template>
        </el-table-column>
        <el-table-column label="生成时间" width="160">
          <template slot-scope="scope">
            <span v-if="scope.row.time">{{scope.row.time | formatTime}}</span>
          </template>
        </el-table-column>

        <el-table-column fixed="right" label="操作" min-width="200">
          <template slot-scope="{row}">
            <el-dropdown size="mini" :split-button="true" type="primary" @click="handleLook(row)"
                         v-if="checkPermissionPoints(3) == 1">查看
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item @click.native="handleEdit(row)" v-if="checkPermissionPoints(4) == 1">
                  编辑
                </el-dropdown-item>
                <el-dropdown-item @click.native="handleDelete(row)" v-if="checkPermissionPoints(2) == 1">删除
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :type="2" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
                  @pagination="getDistributeList" :totalGold="totalGold"/>
    </div>

    <!--查看-->
    <el-dialog title="详细信息" :visible.sync="dialogLookVisible" width="960px" class="distribute-dialog look-dialog"
               top="11vh">
      <el-form label-width="120px" size="mini">
        <el-form-item label="上级用户：">
          <span>{{lookDistribute.upUserName}}</span>
        </el-form-item>
        <el-form-item label="下级用户：">
          <span>{{lookDistribute.userName}}</span>
        </el-form-item>
        <el-form-item label="级别：">
          <span>{{lookDistribute.type | filterType}}</span>
        </el-form-item>
        <el-form-item label="获利时间：">
          <span>{{lookDistribute.relationMoneyTime}}</span>
        </el-form-item>
        <el-form-item label="获利金额：">
          <span>{{lookDistribute.relationMoney}}</span>
        </el-form-item>
        <el-form-item label="资金状态：">
          <span>{{lookDistribute.delStatus | filterStatus}}</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size='small' style="width: 96px" @click="dialogLookVisible = false">取消</el-button>
      </div>
    </el-dialog>

    <!--编辑-->
    <el-dialog title="编辑" :lock-scroll="true" :visible.sync="dialogEditVisible" width="960px" top="11vh"
               class="distribute-dialog">
      <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="auto" size="mini">
        <el-form-item label="上级用户：">
          <span>{{ruleForm.upUserName}}</span>
        </el-form-item>
        <el-form-item label="下级用户：">
          <span>{{ruleForm.userName}}</span>
        </el-form-item>
        <el-form-item label="级别：">
          <span>{{ruleForm.type | filterType}}</span>
        </el-form-item>
        <el-form-item label="获利时间：">
          <span>{{ruleForm.relationMoneyTime}}</span>
        </el-form-item>
        <el-form-item label="获利金额：">
          <span>{{ruleForm.relationMoney}}</span>
        </el-form-item>
        <el-form-item label="资金状态：" prop="delStatus">
          <el-radio-group v-model="ruleForm.delStatus">
            <el-radio disabled :label=0>待确认</el-radio>
            <el-radio :label=1>待领取</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size='small' type="success" style="width: 96px" @click="saveDistribute" :loading="sendLoad">保存
        </el-button>
        <el-button size='small' style="width: 96px" @click="dialogEditVisible = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import Pagination from '@/components/Pagination';
  import {mapGetters} from 'vuex';
  import {permissionPoints} from '@/utils/permission';
  import {baseUrl} from "@/api/constant";
  import {formatDate} from "@/utils/index";
  import {
    batchDistribute, deleteDistribute,
    getDistributedetail,
    getDistributetail,
    getInitDistributeList,
    saveDistribute
  } from "../../../api/finance/finance";
  import {getToken} from "../../../utils/auth";

  export default {
    name: "threeLevelDistribute",
    computed: {
      ...mapGetters([
        'points'
      ])
    },
    data() {
      return {
        keyWords: '',
        select: '1',
        downloadLoading: false,
        multipleSelection: [],
        listLoading: false,
        dialogLookVisible: false,
        dialogEditVisible: false,
        distributeData: [],
        lookDistribute: {},
        total: 0,
        listQuery: {
          page: 1,
          limit: 20,
          upUserName: '',
          userName: '',
          remark: '',
          mechanismName: '',
          startTime: '',
          endTime: '',
          type: '',
          delStatus: ''
        },
        distributeTime: [],
        paramFilters: [],
        ruleForm: {
          id: ''
        },
        totalGold: 0,
        checkThreeStatus: '',
        rules: {
          delStatus: [
            {required: true, message: '请选择资金状态', trigger: 'change'}
          ]
        },
        sendLoad: false
      }
    },
    created() {
      this.getDistributeList();
    },
    methods: {
      getDistributeList() {
        this.listLoading = true;
        getInitDistributeList(this.listQuery).then((res) => {
          this.listLoading = false;
          let retObj = res;
          if (retObj.code == 0 && retObj.data != null) {
            const {items, totalRecord, totalMoney} = retObj.data;
            this.total = totalRecord;
            this.distributeData = items;
            this.totalGold = totalMoney;
          }
        }).catch(() => {
          this.listLoading = false;
        })
      },
      checkPermissionPoints(type) {
        let pointObj = this.points.threeLevelDistribute;
        return permissionPoints(type, pointObj);
      },
      searchDistribute() {//搜索
        this.listQuery.upUserName = '';
        this.listQuery.userName = '';
        this.listQuery.remark = '';
        this.listQuery.mechanismName = '';
        this.listQuery.startTime = '';
        this.listQuery.endTime = '';

        if (this.distributeTime && this.distributeTime.length > 0) {
          this.listQuery.startTime = this.distributeTime[0];
          this.listQuery.endTime = this.distributeTime[1];
        } else {
          if (this.keyWords == '' || this.keyWords == undefined) {
            return this.$message.info({message: '请输入搜索内容', duration: 1000});
          }
        }

        if (this.select == 1) {
          this.listQuery.upUserName = this.keyWords;
        } else if (this.select == 2) {
          this.listQuery.userName = this.keyWords;
        } else if (this.select == 3) {
          this.listQuery.remark = this.keyWords;
        } else if (this.select == 4) {
          this.listQuery.mechanismName = this.keyWords;
        }

        this.listQuery.page = 1;
        this.getDistributeList();
      },
      resetSearch() {
        this.select = '1';
        this.keyWords = '';
        this.listQuery.upUserName = '';
        this.listQuery.userName = '';
        this.listQuery.remark = '';
        this.listQuery.mechanismName = '';
        this.listQuery.startTime = '';
        this.listQuery.endTime = '';
        this.distributeTime = [];
        this.listQuery.type = '';
        this.listQuery.delStatus = '';
        this.$refs.multipleTable.clearFilter();
        this.$refs.multipleTable.clearSelection();
        this.listQuery.page = 1;
        this.getDistributeList();
      },
      filterChange(value) {//过滤
        let row = null;
        let val = null;
        for (const i in value) {
          row = i; // 保存 column-key的值，如果事先没有为column-key赋值，系统会自动生成一个唯一且恒定的名称
          val = value[i];
        }
        const filter = [{
          row: row,
          op: 'contains',
          value: val
        }];
        this.setFilter(filter)
      },
      setFilter(filters) {
        for (let i in filters) {
          let filter = null;
          for (let j in this.paramFilters) {
            if (filters[i]['row'] === this.paramFilters[j]['row']) {
              filter = this.paramFilters[j];
            }
          }

          if (filter == null) {
            this.paramFilters.push({'row': filters[i].row, 'op': filters[i].op, 'value': filters[i].value});
          } else {
            filter.value = filters[i].value;
            filter.op = filters[i].op;
          }
        }

        this.paramFilters.forEach(obj => {
          if (obj.row == 'type') {
            this.listQuery.type = String(obj.value);
          }
          if (obj.row == 'delStatus') {
            this.listQuery.delStatus = String(obj.value);
          }
        });
        this.listQuery.page = 1;
        this.getDistributeList();
      },
      toggleSelection(rows) {
        if (rows) {
          if (this.multipleSelection.length > 0) {
            let selects = this.commonSelection();
            if (selects.status.includes(1) || selects.status.includes(2)) {
              return this.$alert('请勾选待确认的记录，再进行批量修改', '提示', {
                confirmButtonText: '确定',
                type: 'warning',
                callback: action => {}
              });
            }

            this.$confirm('确定将列表中勾选的记录修改为待领取？', '批量管理', {
              type: 'warning',
              confirmButtonText: '确定',
              cancelButtonText: '取消'
            }).then(() => {
              this.batchPass(selects);
            }).catch(() => {
              this.clearSelect();
            });
          }
        } else {
          this.clearSelect();
        }
      },
      clearSelect() {
        this.$refs.multipleTable.clearSelection();
        this.$refs.multipleTable.clearFilter();
        if (this.listQuery.delStatus) {
          this.listQuery.delStatus = '';
          this.listQuery.page = 1;
          this.getDistributeList();
        }
      },
      batchPass(selects) {
        batchDistribute(selects.id).then((res) => {
          let retObj = res;
          if (retObj.code == 0 && retObj.data > 0) {
            this.$refs.multipleTable.clearSelection();
            this.$refs.multipleTable.clearFilter();
            this.listQuery.delStatus = '';
            this.listQuery.page = 1;
            this.getDistributeList();
          }
        });
      },
      getRowKeys(row) {
        return row.id;
      },
      handleSelectionChange(val) {
        this.multipleSelection = val;
      },
      handleLook(row) {//详细信息
        this.dialogLookVisible = true;
        getDistributedetail(row.id).then((res) => {
          let retObj = res;
          if (retObj.code == 0 && retObj.data != null) {
            this.lookDistribute = retObj.data;
          }
        })
      },
      handleEdit(row) {//编辑
        this.dialogEditVisible = true;
        getDistributedetail(row.id).then((res) => {
          let retObj = res;
          if (retObj.code == 0 && retObj.data != null) {
            this.ruleForm = retObj.data;
            this.checkThreeStatus = retObj.data.delStatus;
          }
        })
      },
      saveDistribute() {
        this.$refs.ruleForm.validate((valid) => {
          if (valid) {
            if (this.checkThreeStatus == 0) {
              this.sendLoad = true;
              saveDistribute(this.ruleForm.id).then((res) => {
                let retObj = res;
                this.sendLoad = false;
                if (retObj.code == 0 && retObj.data == 1) {
                  this.dialogEditVisible = false;
                  this.$refs.ruleForm.resetFields();
                  this.$message.success({message: '保存成功', duration: 2000});
                  this.getDistributeList();
                } else {
                  this.$message.error({message: '保存失败，请重试', duration: 2000});
                }
              }).catch(() => {
                this.sendLoad = false;
              })
            } else {
              this.$message.info({message: '资金状态为待确认的三级分销可修改', duration: 1000});
            }
          }
        })
      },
      commonSelection() {
        let row = {};
        let value = this.multipleSelection;
        if (value && value.length > 0) {
          let arr = [];
          let num = [];
          value.forEach((item) => {
            arr.push(item.id);
            num.push(item.delStatus);
          });
          row.id = arr.join(",");
          row.status = num;
        }
        return row;
      },
      handleDelete(row) {//删除
        this.$confirm('此操作将删除该三级分销记录, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteDistribute(row.id).then((res) => {
            let retObj = res;
            if (retObj.code == 0) {
              if (retObj.data > 0) {
                this.$message.success({message: '删除该三级分销记录成功', duration: 2000});
                this.getDistributeList();
              } else {
                this.$message.error({message: '删除该三级分销记录失败，请重试', duration: 2000});
              }
            }
          })
        }).catch((err) => {
        });
      },
      handleExportExcel() {//导出
        let ids = '';
        let row = this.commonSelection();
        if (row && Object.keys(row).length != 0) {
          ids = row.id;
        } else {
          return this.$message.info({message: '请勾选要导出的三级分销', duration: 2000});
        }

        this.downloadLoading = true;
        this.axios.defaults.headers.common["tk"] = getToken();
        this.axios(
          {
            method: 'POST',
            url: baseUrl + '/relationMoney/export_relation_money',
            data: {
              'ids': ids,
              'upUserName': this.listQuery.upUserName,
              'userName': this.listQuery.userName,
              'remark': this.listQuery.remark,
              'startTime': this.listQuery.startTime,
              'endTime': this.listQuery.endTime,
              'mechanismName': this.listQuery.mechanismName,
              'type': this.listQuery.type,
              'delStatus': this.listQuery.delStatus
            },
            responseType: 'blob' //设置响应的数据类型为一个包含二进制数据的 Blob 对象，必须设置
          }
        ).then(response => {
          if (response.status == 200) {
            const time = formatDate((new Date()), 'yyyy-MM-dd hhmmss');
            const blob = new Blob([response.data], {type: 'application/vnd.ms-excel'});
            let fileName = `三级分销报表${time}.xls`;

            if (window.navigator && window.navigator.msSaveOrOpenBlob) {//兼容ie
              window.navigator.msSaveBlob(blob, fileName)
            } else {
              const linkNode = document.createElement('a');

              linkNode.download = fileName;
              linkNode.style.display = 'none';
              linkNode.href = URL.createObjectURL(blob);
              document.body.appendChild(linkNode);
              linkNode.click();

              URL.revokeObjectURL(linkNode.href);
              document.body.removeChild(linkNode);
            }
            this.$refs.multipleTable.clearSelection();
            this.$refs.multipleTable.clearFilter();
            this.listQuery.page = 1;
            this.getDistributeList();
          } else {
            this.$message.error({message: `导出失败，请重试【${response.status}】`, duration: 2000});
          }

          this.downloadLoading = false;
        });
      },
    },
    filters: {
      filterType(type) {
        if (type == 0) {
          return '二级';
        } else if (type == 1) {
          return '三级';
        }
      },
      filterStatus(type) {
        if (type == 0) {
          return '待确认';
        } else if (type == 1) {
          return '待领取';
        } else if (type == 2) {
          return '已领取';
        }
      },
      formatTime(time) {
        let date = new Date(time);
        return formatDate(date, 'yyyy-MM-dd hh:mm:ss');
      }
    },
    components: {
      Pagination
    }
  }
</script>

<style lang="scss" scoped>
  .distribute-container {
    .distribute-search {
      display: flex;
      align-items: center;
      width: 100%;
      height: 80px;
      .page-title {
        padding-left: 20px;
        font-size: 18px;
        font-weight: bold;
        min-width: 200px;
        text-align: left;
        color: rgba(61, 68, 77, 1);
      }
      .search-keyword {
        margin-left: 36px;
        margin-right: 24px;
        width: 470px;
        > > > .el-select .el-input {
          width: 110px;
        }
        > > > .el-input-group__prepend {
          background-color: #fff;
        }
      }
      .search-keyword-reset {
        margin-right: 36px;
      }
      .button-position {
        margin-left: 30px;
      }
      .excel-inout-box {
        margin-left: auto;
        margin-right: 18px;
      }
      .distribute-time {
        margin-right: 8px;
        width: 276px;
      }
    }
    .distribute-table {
      width: 98%;
      margin-left: 18px;
      > > > .el-table td, .el-table th {
        padding: 6px 0px;
      }
      > > > .el-table__header th {
        padding: 0;
        height: 30px;
        line-height: 30px;
      }
      > > > .el-table__column-filter-trigger {
        line-height: 28px;
        i {
          font-size: 18px;
        }
      }
      > > > .el-table__row .cell {
        display: flex;
        align-items: center;
      }
      > > > .el-table__header .has-gutter .cell {
        display: flex;
        justify-content: space-between;
        align-items: center;
      }
      > > > .el-table__fixed-right {
        height: 100% !important;
      }
    }
    .distribute-dialog > > > .el-dialog .el-dialog__header {
      display: flex;
      align-items: center;
      height: 48px;
      background: #F7F8FA;
      padding: 0px 0px 0px 12px;
      .el-dialog__headerbtn {
        top: 15px;
      }
    }
    .look-dialog > > > .el-form-item--mini.el-form-item, .el-form-item--small.el-form-item {
      margin-bottom: 0px;
    }
    .distribute-dialog {
      font-size: 14px;
      color: #606266;
    }
    > > > .el-button {
      line-height: 1.2;
    }
  }
</style>
